<?php

/*
	商品内页

*/
class Goods extends Main {
    //取得分类信息
    //取得商品信息
    public function goodsBasic($goods_id) {
        $sql = "select goods_id,goods_name,market_price,shop_price,goods_sn,cat_id,original_img from goods where goods_id=$goods_id";
        $data = $GLOBALS['db']->getRow($sql);
        return $data;
    }
    //取得商品信息
    public function goodsInfo($goods_id) {
        $sql = "select * from goods where goods_id=$goods_id";
        $data = $GLOBALS['db']->getRow($sql);

        $data = $this->goodsFormat($data);
       // $data['goods_desc'] = $this->goodsDesc($data);
		$data['descs1'] = $data['descs'];


		$gallerys = $this->gallerys($goods_id);

		//$data['descs'] = $this->goodsDescs($data,$goods_id,$data['original_img']);

		foreach($gallerys as $key=>$val)
		{
			$val['img'] = $this->resizeImage($val['img_original'],array(900,900));
			$val['img_original'] = $this->resizeImage($val['img_original'],array(900,900));

			$gallerys[$key] = $val;
		}
		//print_r($gallerys);

        $data['gallery'] = $gallerys;
		$data['img'] = $data['original_img'];
		//$data['original_img'] = $this->waterMark($data['original_img']);
        //print_r($data);

        return $data;
    }
    public function goodsDescs($data,$goods_id,$ori) {
		$p = pathinfo($ori);

		@preg_match("#images/(\d+)/gallery#",$p['dirname'],$img_path);
		$img_path = isset($img_path[1]) ? $img_path[1] : '';

		$str = $data['descs'];
        $name = $data['goods_name'];
        $img = '';
        if (!$str) return $img;
        $sp = preg_split("/\|\|\|/", $str);
        foreach ($sp as $key => $val) {
			preg_match("#[^\./]+\.jpg#",$val,$arr);
			$ps = @$arr[0];
			if($goods_id>=13690)
			{
				$path = './images/'.$img_path.'/con_pic/' . $ps;
			}
			else
			{
				$path = './images/con_pic/' . $ps;
			}

           if (file_exists($path) && $ps) {
                $img.= '<img src="' . $path . '" alt="' . $name . '" />';
            }
			else
			{
				unset($sp[$key]);
			}
        }
		$join =join($sp,"|||");
		$sql = "update goods set descs = '".$this->escapeString($join)."' where goods_id=$goods_id";
		mysql_query($sql);
        return $img;
    }
    /*
    处理商品详细描述
    ':'之后第一个空格换行
    */
    public function goodsDesc($data) {
        $desc = $data['goods_desc'];
        $name = $data['goods_name'];
        $mode = array(
            "/<img.*?src=\"(.*?)\".*?\/>/i",
            "/< br>/"
        );
        $re = array(
            "",
            ""
        );

        preg_match_all($mode[0], $desc, $arr);
        $descs = preg_replace($mode, $re, $desc);

        $src = isset($arr[1]) ? $arr[1] : array();
        $srcs = array();
        foreach ($src as $key => $val) {
           if (file_exists($val)) {
                $srcs[] = '<img src="' . $val . '"  alt="' . $name . '"/>';
            }
        }

        $desc = join($srcs, "") . $descs;
        return $desc;
    }
    //写入商品属性
    public function addGoodsAttr($goods_id, $values, $attr_name) {
       $sp = preg_split("/\|/",$values);
	   $attr_id = $GLOBALS['db']->getOne("select attr_id  from attribute where attr_name='".$attr_name."'");
	   if(!$attr_id)
	   {
		  $data['attr_name'] = $attr_name;
	      $GLOBALS['db']->autoExecute('attribute',$data);
		  $attr_id = mysql_insert_id();
	   }
	   $attr = array();
	   foreach($sp as $key=>$val)
	   {


			$sp1 = preg_split("/#/",$val);
			$k = trim($sp1[0]);
			if(!$k)
				continue;
			$attr['attr_value'] = $this->escapeString($sp1[0]);
			$attr['attr_price'] = @floatval($sp1[1]);
			$attr['goods_id'] = $goods_id;
			$attr['attr_id'] = $attr_id;

			$res[] = $GLOBALS['db']->autoExecute('goods_attr',$attr);
	   }
	   return $res;
    }
    //取得商品相册
    public function gallerys($goods_id) {
        $sql = "select img_original,img_id from goods_gallery where goods_id=$goods_id;";
        $data = $GLOBALS['db']->getAll($sql);
        return $data;
    }
    //取得商品属性
    public function attrs($goods_id, $attr_id = 0) {
        $attr = '';
        if ($attr_id) {
            $attr = " and g.attr_id=$attr_id";
        }
        $sql = "select g.goods_attr_id,g.attr_value,g.attr_price,a.attr_name from goods_attr as g inner join attribute as a on a.attr_id=g.attr_id where g.goods_id=$goods_id $attr";

		$data = $GLOBALS['db']->getAll($sql);
        return $data;
    }
    //取得商品一个属性
    public function attrOne($goods_attr_id) {
        $sql = "select a.attr_name,g.attr_value,g.attr_price from goods_attr as g inner join attribute as a on g.attr_id=a.attr_id  where  goods_attr_id='$goods_attr_id'";
        $data = $GLOBALS['db']->getRow($sql);
        return $data;
    }
    public function goodsAttrs($goods_id) {
        $attr['size'] = $this->attrs($goods_id, 1);
        $attr['color'] = $this->attrs($goods_id, 2);
        $attr['style'] = $this->attrs($goods_id, 3);
        $attr['select'] = $this->attrs($goods_id, 4);
        return $attr;
    }
	public function attrList($goods_id=0) {
        $sql = "select distinct attr_id from goods_attr where goods_id=$goods_id";

		$data = $GLOBALS['db']->getAll($sql);

		$attr = array();
		foreach($data as $key=>$val)
		{
			$attr_id = $val['attr_id'];
			$attrs =  $this->attrs($goods_id,$attr_id);
			$attr_name = @$attrs[0]['attr_name'];
			$attr[$key]['attr_name'] = $attr_name;
			$attr[$key]['list'] = $attrs;
		}

		return $attr;
    }
	//属性列表---数据格式
	public function attrListStr($attr_list){
		$res = array();
		foreach($attr_list as $key=>$val)
		{
			$attr_name = $val['attr_name'];
			foreach($val['list'] as $s_k=>$s_v)
			{
				$str = $s_v['attr_value'].'#'.$s_v['attr_price'];
				$ls[$s_k] = $str;
			}
			$res[$key] = $attr_name.'||'.join($ls,"|");
		}

		return join($res,"|||");
	}
	public function strToAttr($str){
		if(!$str) return '';
		$attr  = preg_split("/\|\|\|/",$str);

		$at = array();
		foreach($attr as $s_k=>$s_v)
		{
			$sp = preg_split("/\|\|/",$s_v);
			$k = trim($sp[0]);
			$v = trim($sp[1]);
			$at[$k] = $v;

		}
		return $at;
	}
    //作为原图
    public function asOriginal($goods_id, $src) {
        $res = false;
        if ($goods_id && $src) {
            $sql = "update goods set original_img='$src' where goods_id=$goods_id";
            $res = mysql_query($sql);
        }
        return $res;
    }
    /*
    获取随机商品
    */
    public function randGoods($cat_ids, $rand_size = 4) {
        $rand_goods = array();
        if (empty($cat_ids)) {
            $where_cat = '';
        } else {
            for ($i = 0; $i < count($cat_ids); $i++) {
                $cat_ids[$i] = "cat_id='" . $cat_ids[$i] . "'";
            }
            $where_cat = join(" or ", $cat_ids);
            $where_cat = "and (" . $where_cat . ")";
        }
        $i = 0;
        while (True) {
            if ($i > 3) break;

            $sql = "select goods_id,cat_id,goods_name,market_price,shop_price,goods_number,original_img,goods_thumb from goods
			where goods_id <= round(rand()*(select count(*) from goods))-" . $rand_size . " and  goods_number !=0 ".GOODS_DELETE_SHOW." " . $where_cat . " order by goods_id desc  limit 0," . $rand_size . " ";

			$rand_goods = $GLOBALS['db']->getAll($sql);
            if (count($rand_goods) >= $rand_size) break;

            $i++;
        }
        foreach ($rand_goods as $key => $val) {
            $val = $this->goodsFormat($val);
            $rand_goods[$key] = $val;
        }
        return $rand_goods;
    }
    //取得最新商品
    public function newGoods($start = 0, $size = 10) {
        $sql = "select goods_name,goods_id,original_img,market_price,shop_price from goods where  goods_sn!='free gift' ".GOODS_DELETE_SHOW." order by goods_id desc limit " . $start . "," . $size . ";";

		$data = $GLOBALS['db']->getAll($sql);
        foreach ($data as $key => $val) {
            $val = $this->goodsFormat($val);
            $data[$key] = $val;
        }

        return $data;
    }
	//取得商品列表中的id
	public function goodsIds($list){
		$ids = array();
		foreach($list as $key=>$val)
		{
			$ids[] = $val['goods_id'];
		}
		return $ids;
	}
	//商品点击
	public function goodsClicks($goods_id){
		$sql = "update goods set click_count=click_count+1,goods_thumb='".time()."' where goods_id=$goods_id";
		mysql_query($sql);
	}
    //取得当天浏览最多的商品
    public function toDayGoods($size=12) {
        $today = mktime(0, 0, 0, date('m') , date('d') , date('Y'));
		$top_ids = $this->goodsIds($this->clickTop());
		$where = 'goods_id!='.join($top_ids,' and goods_id!=');

        $sql = "select original_img,goods_name,market_price,shop_price,goods_id from  goods where ($where) and goods_thumb>='" . $today . "' and goods_sn!='free gift'
		 ".GOODS_DELETE_SHOW." order by click_count desc limit 0,$size ";
		$data = $GLOBALS['db']->getAll($sql);
        foreach ($data as $key => $val) {
            $val = $this->goodsFormat($val);
            $data[$key] = $val;
        }
        return $data;
    }
    //取得点击量最高的
    public function clickTop() {
        $sql = "select original_img,goods_name,market_price,shop_price,goods_id from  goods where goods_sn!='free gift' ".GOODS_DELETE_SHOW." order by click_count desc limit 0,12 ";
        $data = $GLOBALS['db']->getAll($sql);
        foreach ($data as $key => $val) {
            $val = $this->goodsFormat($val);
            $data[$key] = $val;
        }
        return $data;
    }
    //free gift
    public function freeGift() {
        $sql = "select goods_name,original_img,goods_id,shop_price from goods where goods_sn='free gift';";
        $data = $GLOBALS['db']->getAll($sql);
        foreach ($data as $key => $val) {
            $val = @$this->goodsFormat($val);
            $data[$key] = $val;
        }
        return $data;
    }
    //格式化商品信息
    public function goodsFormat($goods) {


        $goods['market_priced'] = $this->priceFormat($goods['market_price']);
        $goods['shop_priced'] = $this->priceFormat($goods['shop_price']);
		$goods['add_time'] =  @$this->dateFormat($goods['add_time']);
        //$comment			    = getComments($goods['goods_id']);
        //$goods['review']        = $comment['info'];
        $goods['goods_name'] = ucwords($goods['goods_name']);
       // $goods['url'] = $this->buildUri($goods['goods_name'], $goods['goods_id'], GOODS_NAME);
		$goods['url'] = $this->buildUri($goods['goods_name'], 'goods.php?id='.$goods['goods_id']);
        $goods['attr_list'] = @$this->attrList($goods['goods_id']);
        $save = $goods['market_price'] - $goods['shop_price'];
        $off = @round(($save / $goods['market_price']) * 100);
        $goods['off'] = $off . '%';
        $goods['save_money'] = $save;
        $goods['goods_thumb'] = $this->resizeImage($GLOBALS['_SEP'].'/'.$goods['original_img'],$GLOBALS['_CFG']['thumb_size']);
        $goods['save_moneyd'] = $this->priceFormat($save);
		$h['h3'] = $h3 = $GLOBALS['db']->getOne("select count(*) from review where id=".$goods['goods_id']." and type=3 and score=3");
		$h['h2'] = $h2 = $GLOBALS['db']->getOne("select count(*) from review where id=".$goods['goods_id']." and type=3 and score=2");
		$h['h1'] = $h1 = $GLOBALS['db']->getOne("select count(*) from review where id=".$goods['goods_id']." and type=3 and score=1");
		$haop = $h3*100+$h2*50+$h1*0+($h3+$h2+$h1)*100;
		$goods['h']= $h;

        return $goods;
    }
    //取得分类ids
    public function ids($cat_id) {
        $sons = $GLOBALS['Cate']->categoryTree($cat_id,true,false);

        $ids = array();
        foreach ($sons as $key => $val) {
            $ids[] = $val['cat_id'];
        }
        $ids[] = $cat_id;
        return $ids;
    }
    //取得分类商品列表
    public function goodsList($start = 0, $size = 10, $condition = '',$fields='') {
        $sql = "select * from goods  $condition limit $start,$size ";

        $data = $GLOBALS['db']->getAll($sql);

        foreach ($data as $key => $val) {
			$val['time'] = $val['add_time'];
            $val = $this->goodsFormat($val);

            $data[$key] = $val;
        }

        return $data;
    }
	//特色商品
	public function freauredGoods($start,$size,$sn,$condition){
		$sql = "select goods_id from goods where style_name='".$sn."' $condition  limit $start,$size";

		$data = $GLOBALS['db']->getAll($sql);
		foreach($data as $key=>$val)
		{
			$ids[] = $val['goods_id'];
		}
		$where = 'goods_id='.join($ids," or goods_id=");

		$sql = "select goods_name,shop_price,market_price,original_img,goods_id from goods where $where ";

		$goods_list = $GLOBALS['db']->getAll($sql);
		foreach($goods_list as $key=>$val)
		{
			$val = $GLOBALS['Goods']->goodsFormat($val);
			$goods_list[$key] = $val;
		}
		return $goods_list;

	}
	//商品编辑
	public function goodsEdit($data=array(),$dir_name=array()){

		if($data) $_POST = $data;

		$goods_name   = !empty($_POST['goods_name']) ? $_POST['goods_name'] : 0;
		$goods_sn   = !empty($_POST['goods_sn']) ? $_POST['goods_sn'] : '';
		$original_img   = !empty($_POST['original_img']) ? $_POST['original_img'] : '';
		$shop_price = !empty($_POST['shop_price']) ? $_POST['shop_price'] : 0;
		$market_price = !empty($_POST['market_price']) ? $_POST['market_price'] : 0;
		$cat_id = empty($_POST['cat_id']) ? '' : intval($_POST['cat_id']);
		$brand_id = empty($_POST['brand_id']) ? '' : intval($_POST['brand_id']);
		$attr = !empty($_POST['attr']) ? $_POST['attr'] : '';
		$keywords = !empty($_POST['keywords']) ? $_POST['keywords'] : '';
		$goods_brief = !empty($_POST['goods_brief']) ? $_POST['goods_brief'] : '';
		$goods_number = !empty($_POST['goods_number']) ? $_POST['goods_number'] : '';
		$goods_desc = !empty($_POST['goods_desc']) ? $_POST['goods_desc'] : '';

		$descs = !empty($_POST['descs']) ? $_POST['descs'] : '';
		$title = !empty($_POST['title']) ? $_POST['title'] : '';
		$is_delete = !empty($_POST['is_delete']) ? intval($_POST['is_delete']) : 0;
		$goods_id = !empty($_POST['goods_id']) ? intval($_POST['goods_id']) : 0;
		$imgs  = !empty($_POST['imgs']) ? $_POST['imgs'] : '';



		if (!$goods_id)
		{

		  $sql = "INSERT INTO goods (goods_name,original_img, goods_sn,cat_id, shop_price, market_price,keywords, goods_brief,goods_number, goods_desc, add_time, title)" .
			"VALUES ('$goods_name','$original_img', '$goods_sn', '$cat_id', '$shop_price', '$market_price','$keywords', '$goods_brief', '$goods_number',
		  '$goods_desc', '". time() ."', '$title');";

		}
		else
		{
		   $sql = "UPDATE goods SET goods_name = '$goods_name',goods_sn = '$goods_sn',cat_id = '$cat_id',shop_price = '$shop_price',market_price = '$market_price' ,
		   keywords = '$keywords',goods_brief = '$goods_brief', goods_number = '$goods_number',goods_desc = '$goods_desc', title = '$title',descs = '$descs',
		   is_delete = '$is_delete' WHERE goods_id = '$goods_id' LIMIT 1";

		}

		mysql_query($sql);

		/* 商品编号 */
		$goods_id = !$goods_id ? $GLOBALS['db']->insert_id() : $goods_id;
		$img_sp = preg_split("/\|\|\|/",$imgs);
		$img_sp = array_unique($img_sp);
		//商品相册
		$sql2 = "delete from goods_gallery where goods_id=$goods_id";
		mysql_query($sql2);


		if($dir_name)
		{
			if($original_img)
			{
				$img_sp[] = $original_img;
			}
			$name = $goods_id.$goods_name;
			$img_sp = $this->moveImgPath($img_sp,$dir_name,$name);

		}

		foreach($img_sp as $key=>$val)
		{
			if(!$val) continue;
			if(!$original_img && $key==0)
			{
				$sql4 = "update goods set original_img='".$val."' where goods_id=$goods_id";

				mysql_query($sql4);
			}
			$sql3 = "insert into goods_gallery (img_original,goods_id) values('".$val."','".$goods_id."')";

			mysql_query($sql3);

		}


		//处理商品属性
		if(!empty($attr))
		{

			$sql1 = "delete from goods_attr where goods_id=$goods_id";
			mysql_query($sql1);
			foreach($attr as $key=>$val)
			{
				$val = trim($val);
				if(!($val)) continue;
				$attr_name = $key;
				$attr_values = $val;

				$this->addGoodsAttr($goods_id,$attr_values,$attr_name);
			}

		}

		return true;
	}
	//移动图片
	private function moveImgPath($img_arr,$path,$name){
		$imgs = array();

		foreach($img_arr as $key=>$val)
		{
			if(!$val) continue;
			$old_path = $path['old'].'/'.$val;

			$new_name = 'images/'.date('ymdHi').'/'.$this->buildUri($name,-1).$key;  //文件夹的格式 年月日分钟
			$new_path = $path['new'].'/'.$new_name;

			if(file_exists($old_path))
			{

				$n_info = pathinfo($new_path);

				if(!file_exists($n_info['dirname']))
				{
					$this->mkdirs($n_info['dirname']);
				}
				if(file_exists($new_path))
				{
					$new_path = $new_path.time();
				}
				$new_path = $new_path.'.jpg';
				if(copy($old_path,$new_path))
				{
					$imgs[] = $new_name.'.jpg';
				}
			}
		}

		return $imgs;
	}
	//特征商品列表 arr = array('bracelet','necklace','ring','Brooch',...);
	public function featureGoods($arr,$size=5){
		$res = array();
		$ids = array();
		foreach($arr as $key=>$val)
		{
			$val = strtolower($val);
			$join = join($ids," and ");
			$join = !empty($ids) ? "and($join)" :  '';

			$where = " where instr(goods_name,' ".$val."') $join  order by click_count desc";

			$list = $this->goodsList(0,$size,$where);
			foreach($list as $k=>$v)
			{
				$ids[] = " goods_id!=".$v['goods_id']." ";
			}
			$res[$val] = $list;

		}
		return $res;
	}

	//价格区间
	public function priceLimit($pre=''){
		$search = @$_SESSION['search'];
		$price = '';
		if(isset($search['price_limit']))
		{
			$pl = $search['price_limit'];
			$en = $pl['end'];
			$st = $pl['start'];
			if($en>0)
			{
				$price =" and ({$pre}shop_price>=$st and {$pre}shop_price<=$en)";
			}
		}
		return $price;
	}
	//取得最近访问的商品
	public function recentGoods(){
		$rec = !empty($_COOKIE['recent_goods']) ? $_COOKIE['recent_goods'] : array();
		$rec = array_unique($rec);
		foreach($rec as $key=>$val)
		{
			if(!$val) unset($rec[$key]);
		}
		$goods_list = array();
		if($rec)
		{
			$join = "goods_id in (".join(',',$rec).")";
			$where = " where $join order by goods_thumb desc";
			$goods_list = $this->goodsList(0,10,$where);
		}
		foreach($goods_list as $key=>$val)
		{
			$keywords = preg_split("/,/",$val['keywords']);
			foreach($keywords as $k=>$v)
			{
				$v = "<a href='index.php?kw=$v'>$v</a>";
				$keywords[$k] = $v;
			}
			$val['keywords'] = join("、",$keywords);
			$goods_list[$key] = $val;

		}
		return $goods_list;


	}
	//取得相似的商品
	public function relateGoods($start=0,$size=10,$str){

		if(!$str)
		return false;

		require (ROOT_PATH . '/includes/class/search.class.php');
		$keys = new Keywords($str);
		$list = $keys->getSearchList($start, $size);
		return $list;
	}
	//删除商品
	public function goodsDelete($goods_id=0){
		$sql1 = "delete from goods where goods_id=$goods_id;";
		$sql2 = "delete from goods_gallery where goods_id=$goods_id;";
		$sql3 = "delete from goods_attr where goods_id=$goods_id;";
		$res1 = mysql_query($sql1);
		$res2 = mysql_query($sql2);
		$res3 = mysql_query($sql3);
		$res = ($res1 && $res2 && $res3);

		return $res;

	}

	//取得套餐商品
	public function goodsPackage($start=0,$size=10,$where='',$goods=true){
		 $data = $GLOBALS['db']->getAll("select * from goods_package $where limit $start,$size");
		 if(!$data)
		 {
		   $data = $GLOBALS['db']->getAll("select * from goods_package where 1 limit $start,$size");
		 }
		 foreach($data as $key=>$val)
		{
			$val['priced'] = $this->priceFormat($val['price']);
			$val['shipping_feed'] = $this->priceFormat($val['shipping_fee']);
			$p_ids = preg_split("/,/",$val['p_ids']);
			$join  ="goods_id=".join($p_ids," or goods_id=");
			$shop_price = 0;
			if($goods)
			{
				$goods_list = $this->goodsList(0,10," where $join ");


				foreach($goods_list as $_k=>$_v)
				{
					$shop_price+= $_v['shop_price'];
				}
				$val['save_moneyd'] = $this->priceFormat($shop_price-$val['price']);
				$val['goods_list'] = $goods_list;
			}

			$data[$key] = $val;

		 }
		 return $data;

	}

	public function packGoodsPrice($pack){
		$res = array();

		foreach($pack as $key=>$val)
		{
			if($val)
			{
				$p = $this->goodsPackage(0,1," where p_id=$val",false);
				$p = @$p[0];


				@$res['fee']['price'] += $p['price'];
				@$res['fee']['shipping_fee'] += $p['shipping_fee'];
				$res['list'][$val] = $p;
			}
		}
		return $res;
	}

	//设置相册
	public function setGallery($goods_id,$gallery){
		$sql = "delete from goods_gallery where goods_id=$goods_id";

		mysql_query($sql);
		foreach($gallery as $key=>$val)
		{
			if($key==0)
			{
				$sql = "update goods set original_img='$val' where goods_id=$goods_id";
				mysql_query($sql);
			}
			$data = array();
			$data['goods_id'] = $goods_id;
			$data['img_original'] = $val;
			$GLOBALS['db']->autoExecute('goods_gallery',$data);
		}

	}
}
?>

